package com.sso.oa.controller;

import com.sso.common.dto.ApiResponse;
import com.sso.common.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 单点登录控制器
 */
@Controller
public class SsoController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 处理单点登录请求
     * 
     * @param token 从门户系统传递的令牌
     * @return 重定向到首页
     */
    @GetMapping("/sso")
    public String handleSsoLogin(@RequestParam("token") String token) {
        try {
            // 验证令牌
            Map<String, Object> userInfo = JwtUtil.validateSsoToken(token);
            String username = (String) userInfo.get("username");
            
            // 验证令牌是否存在于Redis中
            String redisToken = (String) redisTemplate.opsForValue().get("token:" + username);
            if (redisToken == null || !redisToken.equals(token)) {
                return "redirect:/login?error=invalid_token";
            }
            
            // 获取用户权限
            List<SimpleGrantedAuthority> authorities = null;
            if (userInfo.get("authorities") instanceof List) {
                authorities = ((List<?>) userInfo.get("authorities")).stream()
                        .map(auth -> new SimpleGrantedAuthority(auth.toString()))
                        .collect(Collectors.toList());
            }
            
            // 创建认证对象
            Authentication authentication = new UsernamePasswordAuthenticationToken(
                    username, null, authorities);
            
            // 设置认证信息
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 重定向到首页
            return "redirect:/";
        } catch (Exception e) {
            return "redirect:/login?error=invalid_token";
        }
    }
    
    /**
     * 验证单点登录令牌
     */
    @GetMapping("/api/validate-token")
    @ResponseBody
    public ApiResponse<Map<String, Object>> validateToken(@RequestParam("token") String token) {
        try {
            Map<String, Object> userInfo = JwtUtil.validateSsoToken(token);
            return ApiResponse.success("令牌验证成功", userInfo);
        } catch (Exception e) {
            return ApiResponse.error("令牌验证失败: " + e.getMessage());
        }
    }
}